package com.dinghui.pay.controller.union;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.dinghui.pay.common.ResponseResult;
import com.dinghui.pay.pojo.TbOrder;
import com.dinghui.pay.pojo.TbUser;
import com.dinghui.pay.pojo.param.PayOrderParam;
import com.dinghui.pay.pojo.param.UpdateNativeOrderStatusParam;
import com.dinghui.pay.service.OrderService;
import com.dinghui.pay.service.UserService;
import com.dinghui.pay.utils.JwtUtils;
import com.dinghui.pay.utils.RedisUtils;
import com.unionpay.acp.sdk.AcpService;
import com.unionpay.acp.sdk.SDKConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @version 1.0
 * @author: trt
 * @description:
 * @create: 2021-06-05 19:46
 */
// 网站 银联业务接口
@RestController
@RequestMapping("/api/unionpay/web")
public class NativeController {

    @Autowired
    private SDKConfig config;

    @Autowired
    private AcpService acpService;

    @Value("${unionpay.mch-id}")
    private String mchId;

    @Value("${unionpay.frontUrl}")
    private String frontUrl;

    @Value("${unionpay.backUrl}")
    private String backUrl;

    @Value("${unionpay.orderUrl}")
    private String orderUrl;

    @Value("${unionpay.wapFrontUrl}")
    private String wapFrontUrl;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private JwtUtils jwtUtils;


    /**
     * 创建native支付订单
     *
     * https://open.unionpay.com/tjweb/acproduct/list?apiSwcld=448&index=2
     *
     *
     */
    // native付款
    @PostMapping("/nativePayOrder")
    public ResponseResult nativePayOrder(@RequestBody PayOrderParam param, @RequestHeader HashMap header) {
        String token = header.get("token").toString();
        Long userId = Long.parseLong(jwtUtils.getClaimByToken(token).getSubject());
        int orderId = param.getOrderId();
        TbUser user = new TbUser();
        user.setUserId(userId);
        long count = userService.getCount(user);
        //判断用户是否存在
        if (count == 0) {
            return ResponseResult.error("用户不存在");
        }

        //判断用户是否拥有这个订单，并且订单是未支付状态
        TbOrder order = new TbOrder();
        order.setUserId(userId.intValue());
        order.setId(orderId);
        order.setStatus(1);
        count = orderService.getCount(order);
        if (count == 0) {
            return ResponseResult.error("不是有效的订单");
        }

        // todo 验证购物券是否有效
        // todo 验证团购活动是否有效

        //查询订单详情信息
        order = new TbOrder();
        order.setId(orderId);
        order = orderService.getOne(order); //订单对象
        String amount = order.getAmount().multiply(new BigDecimal("100")).intValue() + ""; //微信‘银联最小单位是分，不能有小数点，所以金额*100

        try {
            Map<String, String> requestData = new HashMap<String, String>();
            requestData.put("version", "5.0.0");    //版本号，全渠道默认值
            requestData.put("encoding", "UTF-8");  //字符集编码，可以使用UTF-8,GBK两种方式
            requestData.put("signMethod", "01"); //签名方法
            requestData.put("txnType", "01");     //交易类型 ，01：消费
            requestData.put("txnSubType", "01");  //交易子类型， 01：自助消费
            requestData.put("bizType", "000201"); //业务类型，B2C网关支付，手机wap支付
            requestData.put("channelType", "07"); //渠道类型；07：PC,平板  08：手机
            requestData.put("merId", mchId);      //商户号码，请改成自己申请的正式商户号或者open上注册得来的777测试商户号
            requestData.put("accessType", "0");   //接入类型，0：直连商户
            requestData.put("orderId", order.getCode());   //商户订单号
            //订单发送时间，取系统时间，格式为YYYYMMDDhhmmss，必须取当前时间，否则会报txnTime无效
            requestData.put("txnTime", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
            requestData.put("currencyCode", "156");  //交易币种（境内商户一般是156 人民币）
            requestData.put("txnAmt", amount);  //交易金额，单位分，不要带小数点
            requestData.put("frontUrl", frontUrl);
            requestData.put("backUrl", backUrl);
            requestData.put("payTimeout", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date().getTime() + 15 * 60 * 1000));
            Map<String, String> submitFromData = acpService.sign(requestData, "UTF-8");
            String requestFrontUrl = config.getFrontRequestUrl();
            //生成自动跳转的Html表单
            String htmlCode = AcpService.createAutoFormHtml(requestFrontUrl, submitFromData, "UTF-8");

            if (htmlCode!=null && htmlCode.length()>0) {
                //更新本地商品订单信息，但是不更新商品订单状态
                order.setPaymentType(3); //支付类型
                order.setId(order.getId());  // 查询条件
                orderService.update(order);
                return ResponseResult.success("htmlCode", htmlCode);
            } else {
                return ResponseResult.error("支付订单创建失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("银联支付模块故障");
        }
    }


    /**
     * 编写前端回调web方法
     */
    // 接收银联页面跳转请求
    @RequestMapping("/recvFrontResponse")
    public void recvFrontResponse(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        HashMap<String, String> reqParam = new HashMap<>();
        Enumeration<String> enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String value = request.getParameter(name);
            reqParam.put(name, value);
        }

        Map<String, String> valideData = null;
        String htmlCode = null;
        if (!reqParam.isEmpty()) {
            Iterator<Map.Entry<String, String>> it = reqParam.entrySet().iterator();
            valideData = new HashMap<String, String>(reqParam.size());
            while (it.hasNext()) {
                Map.Entry<String, String> e = it.next();
                String key = (String) e.getKey();
                String value = (String) e.getValue();
                valideData.put(key, value);
            }
        }

        if (acpService.validate(valideData, "UTF-8")) {
            System.out.println("前端回调签名验证成功");

            String respCode = request.getParameter("respCode");
            String queryId = request.getParameter("queryId");
            String code = request.getParameter("orderId");
            if ("00".equals(respCode)) {
                TbOrder tbOrder = new TbOrder();
                tbOrder.setCode(code); // 查询条件
                tbOrder.setStatus(2);
                tbOrder.setPaymentType(3);
                tbOrder.setPrepayId(queryId);
                orderService.update(tbOrder);
            }
        }
        response.sendRedirect(orderUrl); // 从定向地址
    }




}